package com.douqu.game.core.entity.ext.data.boon;

import com.bean.core.buffer.ByteBuffer;
import com.douqu.game.core.config.activity.SevenActivitiesConfig;
import com.douqu.game.core.config.activity.SevenActivitiesRewardConfig;
import com.douqu.game.core.config.activity.SevenTabConfig;
import com.douqu.game.core.e.E_SevenDayActiType;
import com.douqu.game.core.entity.Player;
import com.douqu.game.core.entity.ext.BagInfo;
import com.douqu.game.core.entity.ext.data.BaseData;
import com.douqu.game.core.entity.world.WorldRankData;
import com.douqu.game.core.factory.DataFactory;
import com.douqu.game.core.factory.SevenDayFactory;
import com.douqu.game.core.factory.WorldInfoFactory;
import com.douqu.game.core.protobuf.SGCommonProto;
import com.douqu.game.core.util.LogUtils;
import com.douqu.game.core.util.time.TimeData;
import com.douqu.game.core.util.time.TimeUtils;

import java.util.*;

/**
 * Created by dengbo on 2018/9/19 0019.
 */
public class SevenDayData extends BaseData {

    /**开服活动奖励列表**/
    private List<SevenDayBean> sevenDayRecordList;

    //玩家累计积分
    private int integral;

    //积分礼包领取列表
    private List<Integer> integralRewardList;

    //开服红利是否购买
    private boolean isBuyWelfareGift;

    private Player player;

    public SevenDayData(Player player){
        this.player = player;
        this.sevenDayRecordList =new ArrayList<>();
        this.integral = 0;
        this.integralRewardList=new ArrayList<>();
        this.isBuyWelfareGift =false;
    }

    /**
     * 初始化
     */
    public  void initSevenDay(){
        this.sevenDayRecordList =new ArrayList<>();
        List<SevenActivitiesConfig> list = DataFactory.getInstance().getDataList(DataFactory.SEVEN_DAY_REWARD);
        for (SevenActivitiesConfig config:list){
            //每日奖励直接是可领取状态
            if (config.eventType == SevenDayFactory.EVENT_TYPE_1){
                SevenTabConfig tabConfig= DataFactory.getInstance().getGameObject(DataFactory.SEVEN_TAB, config.groupId);
                sevenDayRecordList.add(new SevenDayBean(config.id,SevenDayFactory.STATE_2,tabConfig.type,config.conditionParam));
            }
        }
        this.integral = 0;
        this.integralRewardList = new ArrayList<>();
        this.isBuyWelfareGift = false;
    }

    /**
     * 领取7天乐奖励礼包
     * @param rewardId 奖励id
     * @return
     */
    public Boolean getAllReward(int rewardId){
        //通过id取的配置
        SevenActivitiesConfig config = DataFactory.getInstance().getGameObject(DataFactory.SEVEN_DAY_REWARD,rewardId);
        if (config == null){
            LogUtils.error("seven day config is null ! id ="+rewardId);
            return false;
        }

        SevenTabConfig tabConfig= DataFactory.getInstance().getGameObject(DataFactory.SEVEN_TAB, config.groupId);
        // 是否在领奖时间内
        if (!isGetRewardTime(tabConfig)){
            LogUtils.error("is not In Time! id ="+rewardId);
            return false;
        }
        //等级不够
        if (tabConfig.openLevel > player.getLv()){
            LogUtils.error("lv is enough ! id ="+rewardId);
            return false;
        }
        //类型和发放方式不对
        if (tabConfig.type != E_SevenDayActiType.SEVEN_DAY_REWARD.getCode() && config.rewardMod !=SevenDayFactory.REWARD_MOD_1){
            LogUtils.error("Wrong type of package. id=" + config.id+"type=" + tabConfig.type);
            return false;
        }
        SevenDayBean sevenDay = null;
        for (SevenDayBean sevenDayBean:sevenDayRecordList){
            if (sevenDayBean.getId() == config.getId()){
                sevenDay = sevenDayBean;
                break;
            }
        }
        if (sevenDay == null){
            LogUtils.error("this reward is null !!!");
            return false;
        }
        //有该奖励记录 查询领取状态
        if (sevenDay.getState() != SevenDayFactory.STATE_2 ){
            LogUtils.error("The gift package does not meet the requirements. id=" + config.id);
            return false;
        }
        //获得奖励
        BagInfo bagInfo = player.getExtInfo(BagInfo.class);
        bagInfo.addGoods(config.rewardItem);
        //修改领取状态
        sevenDay.setState(SevenDayFactory.STATE_3);
        //添加积分
        addActivities(config.rewardCurrency);
        return true;
    }

    /**
     * 检测目标状态
     * @param target 目标id
     * @param value 值
     */
    public void checkAllRewardState(int target,int... value){
//        for (SevenDayBean bean:sevenDayRecordList){
//            //LogUtils.info("__________________检测前后礼包的信息id= "+bean.getId()+"状态 ="+bean.getState()+"值"+Arrays.toString(bean.value));
//        }
        //LogUtils.info("收到检测的信息 检测目标为="+target+"值为="+ Arrays.toString(value));
       List<SevenActivitiesConfig> activitiesConfigList= DataFactory.getInstance().getDataList(DataFactory.SEVEN_DAY_REWARD);
          for (SevenActivitiesConfig config:activitiesConfigList){
              if (config.eventType == target && config.rewardMod == SevenDayFactory.REWARD_MOD_1) {
                  //LogUtils.info("开始检测id="+config.getId() +"的礼包状态"+Arrays.toString(config.conditionParam)+"" );
                  checkSevenRewardState(config, value);
                  //LogUtils.info("目标为"+target+"的消息+id为"+config.id+"检测完毕");
              }
          }
//        for (SevenDayBean bean:sevenDayRecordList){
//            LogUtils.info("+++++++++++++++++++++检测完后礼包的信息id= "+bean.getId()+"状态 ="+bean.getState()+"值"+Arrays.toString(bean.value));
//        }

    }

    /**
     * 7日礼包检测
     * @param config
     * @param value
     */
    private void checkSevenRewardState(SevenActivitiesConfig config, int[] value) {
        // 是否在活动时间内
        SevenTabConfig tabConfig= DataFactory.getInstance().getGameObject(DataFactory.SEVEN_TAB, config.groupId);
        if (tabConfig == null){
            return;
        }
        if (!isInTime(tabConfig)){
            return;
        }
        //获得配置参数
       List<Integer> parameter= new ArrayList<>();
       for (Integer param: config.conditionParam){
           if (param!=0){
               parameter.add(param);
           }
       }
        //获得礼包数据，没有就初始化一个
        SevenDayBean  sevenDayBean=null ;
        for (SevenDayBean bean:sevenDayRecordList) {
            if (bean.getId() == config.id){
                sevenDayBean = bean;
                break;
            }
        }
        if (sevenDayBean == null){
            sevenDayBean = new SevenDayBean(config.id,SevenDayFactory.STATE_1,tabConfig.type,new int[value.length]);
            sevenDayRecordList.add(sevenDayBean);
        }
        else if (sevenDayBean.getState() != SevenDayFactory.STATE_1){
            return;
        }
        //判断是否可领取
        boolean isCanReward = true;
        //参数条件是否正确
        boolean isParamTrue = true;
        int index;
        switch (config.eventType){
            //全部参数都是达到某一个值的目标事件
            case SevenDayFactory.EVENT_TYPE_2:
            case SevenDayFactory.EVENT_TYPE_3:
            case SevenDayFactory.EVENT_TYPE_6:
            case SevenDayFactory.EVENT_TYPE_22:
                if (parameter.size() !=value.length){
                    return;
                }
                sevenDayBean.setValue(value);
                for ( index = 0; index < parameter.size(); index++) {
                    if (value[index] < parameter.get(index)) {
                        isCanReward = false;
                        break;
                    }
                }
                    //可领取修改状态
                if (isCanReward) {
                    sevenDayBean.setState(SevenDayFactory.STATE_2);
                    LogUtils.info(config.id+"礼包变为可领取状态=== type ="+config.eventType +"" +
                            " 值 ="+value);
                }

                break;
            //全部都是累计到某个值的事件
            case SevenDayFactory.EVENT_TYPE_4:
            case SevenDayFactory.EVENT_TYPE_5:
            case SevenDayFactory.EVENT_TYPE_8:
            case SevenDayFactory.EVENT_TYPE_13:
            case SevenDayFactory.EVENT_TYPE_14:
            case SevenDayFactory.EVENT_TYPE_15:
            case SevenDayFactory.EVENT_TYPE_16:
            case SevenDayFactory.EVENT_TYPE_26:
                if (parameter.size() != value.length){
                    return;
                }
                   //累加每一个值
                for (index = 0;index < value.length;index++){
                    sevenDayBean.value[index] = value[index] + sevenDayBean.value[index];
                }
                   //判断是否可领取
                isCanReward = true;
                for (index = 0; index < parameter.size(); index++) {
                    if (sevenDayBean.value[index] < parameter.get(index)) {
                        isCanReward = false;
                        break;
                    }
                }
                   //可领取修改状态
                if (isCanReward) {
                    sevenDayBean.setState(SevenDayFactory.STATE_2);
                    LogUtils.info(config.id+"礼包变为可领取状态=== type ="+config.eventType +"" +
                            " 值 ="+Arrays.toString(value));
                }
                break;
            //固定参数事件 全部参数都为固定值
            case SevenDayFactory.EVENT_TYPE_7:
            case SevenDayFactory.EVENT_TYPE_25:
                if (parameter.size() != value.length){
                    return;
                }
                for (index = 0 ;index < value.length;index++){
                    if (value[index] != parameter.get(index)){
                        isParamTrue = false;
                    }
                }
                if (isParamTrue) {
                    sevenDayBean.setValue(value);
                    sevenDayBean.setState(SevenDayFactory.STATE_2);
                    LogUtils.info(config.id+"礼包变为可领取状态=== type ="+config.eventType +"" +
                            " 值 ="+Arrays.toString(value));
                }
                break;
            //第一个参数需要累加，后面的参数是固定数值的事件
            case SevenDayFactory.EVENT_TYPE_9:
            case SevenDayFactory.EVENT_TYPE_10:
            case SevenDayFactory.EVENT_TYPE_11:
            case SevenDayFactory.EVENT_TYPE_12:
            case SevenDayFactory.EVENT_TYPE_24:
                if (config.conditionParam.length <value.length){
                    for (index = 0;index<value.length;index++){
                        //参数不满足 -1表示该参数不做判断了
                        if (index != 0 && config.conditionParam[index] != -1){
                            if ( value[index] !=config.conditionParam[index])
                            isParamTrue = false;
                            break;
                        }
                    }
                }else {
                    for (index = 0; index < value.length; index++) {
                        //参数不满足
                        if (index != 0 && value[index] !=parameter.get(index)) {
                            isParamTrue = false;
                            break;
                        }
                    }
                }
                if (isParamTrue){
                    sevenDayBean.value[0] = value[0] + sevenDayBean.value[0];
                    if (sevenDayBean.value[0] >= parameter.get(0)){
                        sevenDayBean.setState(SevenDayFactory.STATE_2);
                        LogUtils.info(config.id+"礼包变为可领取状态=== type ="+config.eventType +"" +
                                " 值 ="+Arrays.toString(value));
                    }
                }
                break;
            //参数1是累加，后面的参数是达到的事件
            case SevenDayFactory.EVENT_TYPE_23:
                for (index = 0;index<value.length;index++){
                    if (index != 0 && value[index] < parameter.get(index)){
                        isParamTrue = false;
                    }
                }
                if (isParamTrue){
                    sevenDayBean.value[0] = value[0] + sevenDayBean.value[0];
                    if (sevenDayBean.value[0] >= parameter.get(0)){
                        sevenDayBean.setState(SevenDayFactory.STATE_2);
                        LogUtils.info(config.id+"礼包变为可领取状态=== type ="+config.eventType +"" +
                                " 值 ="+Arrays.toString(value));
                    }
                }
                break;
            //排行榜事件，在某两个名次的区间可领取奖励
            case SevenDayFactory.EVENT_TYPE_18:
            case SevenDayFactory.EVENT_TYPE_17:
            case SevenDayFactory.EVENT_TYPE_19:
            case SevenDayFactory.EVENT_TYPE_20:
            case SevenDayFactory.EVENT_TYPE_21:
                if (parameter.size() == 1 && value[0] >= parameter.get(0)){
                    sevenDayBean.setState(SevenDayFactory.STATE_2);
                    LogUtils.info("某个礼包变为可领取状态=== type ="+config.eventType +"" +
                            " 值 ="+Arrays.toString(value));
                }
                else if (value[0] >= parameter.get(0) && value[1] <= parameter.get(1)){
                    sevenDayBean.setState(SevenDayFactory.STATE_2);
                    LogUtils.info("某个礼包变为可领取状态=== type ="+config.eventType +"" +
                            " 值 ="+Arrays.toString(value));
                }
                break;

        }
    }


    /**
     * 领取积分礼包
     * @param id
     * @return
     */
    public  Boolean getSevenActivities(int id)
    {
        //获得配置信息
        SevenActivitiesRewardConfig config = DataFactory.getInstance().getGameObject(DataFactory.SEVEN_ACTIVITIES_REWARD,id);
        if (config == null){
            LogUtils.error("seven activities config is null ! id ="+id);
            return false;
        }
        //7日礼包积分
        switch (config.type){
            case SevenDayFactory.ACTIVITIES_SEVEN_DAY:
                //积分不足
                if (getIntegral() < config.integral){
                    LogUtils.error("积分不足 integral ="+getIntegral());
                    return false;
                }
                break;
            case SevenDayFactory.ACTIVITIES_OPEN_GIFT:
                // 判断购买人数
//                int count = WorldInfoFactory.getInstance().getBonusCount();
//                if (count < config.integral){
//                    LogUtils.error("购买人数不足 count="+count);
//                    return false;
//                }
                break;
            default:
                LogUtils.error("类型错误 type ="+ config.type);
                return false;
        }
        //已领取过
        if (integralRewardList.contains(config.id)){
            LogUtils.error("已领取过 id="+ config.id);
            return false;
        }
        //获得奖励
        BagInfo bagInfo = player.getExtInfo(BagInfo.class);
        bagInfo.addGoods(config.rewardItem);
        //添加领取记录
        integralRewardList.add(config.id);
        return true;
    }

    /**
     * 添加积分
     * @param activities
     */
    public void addActivities(int activities){
        integral += activities;
    }

    /**
     *已领取的奖励列表获取
     * type 活动类型
     * @return
     */
    public List<SGCommonProto.SevenGiftColumn.Builder> getRewardList(int type){
        checkTopGift();
        List<SGCommonProto.SevenGiftColumn.Builder> list  = new ArrayList<>();
        SGCommonProto.SevenGiftColumn.Builder c ;
        SevenActivitiesConfig config;
        SevenTabConfig tabConfig;
        for (SevenDayBean sevenDayBean:sevenDayRecordList){
            if (type ==sevenDayBean.type ) {
              c = SGCommonProto.SevenGiftColumn.newBuilder();
                c.setActivityId(sevenDayBean.getId());
                config = DataFactory.getInstance().getGameObject(DataFactory.SEVEN_DAY_REWARD,sevenDayBean.getId());
                if (config == null){
                    LogUtils.error("this id is no config id ="+sevenDayBean.getId());
                    continue;
                }
                tabConfig= DataFactory.getInstance().getGameObject(DataFactory.SEVEN_TAB, config.groupId);
                if (tabConfig == null){
                    LogUtils.error("this id is no tab config id ="+config.groupId);
                    continue;
                }
                c.setStatus(sevenDayBean.getState());
                //开服福利类型的活动参数客户端需求参数发1
                if (config.eventType == SevenDayFactory.EVENT_TYPE_1) {
                    c.setParam(1);
                }
                else c.setParam(sevenDayBean.getParams());
                c.setDayCount(tabConfig.tab);
                list.add(c);
            }
        }
        return list;
    }

    /**
     * 检测排行礼包是否可以领取
     */
    private void checkTopGift(){
        //检测开服红利的任务次数
//        int count = WorldInfoFactory.getInstance().getBonusCount();
//        checkAllRewardState(SevenDayFactory.EVENT_TYPE_22, count);

        //检测排行任务是否完成
        WorldRankData worldRankData = WorldInfoFactory.getInstance().getWorldRankData();
        int playerTop;
        playerTop= worldRankData.getRankByPlayer(player, SGCommonProto.E_RANK_TYPE.RANK_TYPE_EXPEDITION);
        if (playerTop != 0){
            checkAllRewardState(SevenDayFactory.EVENT_TYPE_20,playerTop);
        }
        playerTop= worldRankData.getRankByPlayer(player, SGCommonProto.E_RANK_TYPE.RANK_TYPE_INSTANCE);
        if (playerTop != 0){
            checkAllRewardState(SevenDayFactory.EVENT_TYPE_21,playerTop);
        }
        playerTop= worldRankData.getRankByPlayer(player, SGCommonProto.E_RANK_TYPE.RANK_TYPE_MONEY);
        if (playerTop != 0){
            checkAllRewardState(SevenDayFactory.EVENT_TYPE_19,playerTop);
        }
        playerTop= worldRankData.getRankByPlayer(player, SGCommonProto.E_RANK_TYPE.RANK_TYPE_FC);
        if (playerTop != 0){
            checkAllRewardState(SevenDayFactory.EVENT_TYPE_18,playerTop);
        }
    }

    /**
     * 已领取的积分奖励列表
     * @return
     */
    public List<Integer> getActivitiesList(){
        return  integralRewardList;
    }

    /**
     *  是否在活动时间内
     * @return
     */
    public boolean isInTime(SevenTabConfig config){
        TimeData timeData = config.startTime;
        long serverStart = WorldInfoFactory.getInstance().getStartServerTime().getTime();
        Calendar now = Calendar.getInstance();
        return TimeUtils.isInActivityTime(timeData, now, serverStart);
    }

    /**
     *  是否在领奖时间内
     * @return
     */
    public boolean isGetRewardTime(SevenTabConfig config){
        TimeData timeData = config.continuedTime;
        long serverStart = WorldInfoFactory.getInstance().getStartServerTime().getTime();
        Calendar now = Calendar.getInstance();
        return TimeUtils.isInActivityTime(timeData, now,serverStart);
    }

    /**
     * 当前天数
     * @return
     */
    public int getCurrentDays(){
        //开服时间
        Date serverStart = WorldInfoFactory.getInstance().getStartServerTime();
        //当前时间
        Date currentTime = new Date();
        return TimeUtils.dayBetween(serverStart, currentTime);
    }

    @Override
    public void init() {
        initSevenDay();
    }

    @Override
    public void checkInit() {
        if (sevenDayRecordList.isEmpty() )
            init();
    }

    @Override
    public void reset() {
    }

    @Override
    public void checkReset() {

    }

    @Override
    public void writeTo(ByteBuffer buffer) {
        buffer.writeByte(sevenDayRecordList.size());
        for (SevenDayBean bean:sevenDayRecordList){
            buffer.writeInt(bean.getId());
            buffer.writeByte(bean.getState());
            buffer.writeInt(bean.getType());
            buffer.writeByte(bean.getValue().length);
            for (int i =0 ;i< bean.getValue().length;i++){
                buffer.writeInt(i);
            }
        }
        buffer.writeInt(integral);
        buffer.writeByte(integralRewardList.size());
        for (Integer param:integralRewardList){
            buffer.writeInt(param);
        }
        buffer.writeBoolean(isBuyWelfareGift);
    }

    @Override
    public void loadFrom(ByteBuffer buffer) {
        int size = buffer.readByte();
        sevenDayRecordList = new ArrayList<>();
        int id;
        byte state;
        int[] value;
        int length;
        int type;
        for (int i = 0 ;i< size;i++){
            id  = buffer.readInt();
            state = (byte) buffer.readByte();
            type = buffer.readInt();
            length = buffer.readByte();
            value =new int[length];
            for (int j = 0;j<length;j++){
                value[j] = buffer.readInt();
            }
            sevenDayRecordList.add(new SevenDayBean(id,state,type,value));
        }
        integral = buffer.readInt();
        size = buffer.readByte();
        integralRewardList = new ArrayList<>();
        for (int i = 0;i< size;i++){
            integralRewardList.add(buffer.readInt());
        }
        isBuyWelfareGift = buffer.readBoolean();
    }

    public int getIntegral() {
        return integral;
    }

    public boolean isBuyWelfareGift() {
        return isBuyWelfareGift;
    }

    public void setBuyWelfareGift(boolean isBuyWelfareGift) {
        this.isBuyWelfareGift = isBuyWelfareGift;
    }
}
